package com.alibaba.citrus.cr.platform.enhance.facade.service.diff.sap;

import java.util.Date;
import java.util.List;
import java.util.Objects;

import com.alibaba.citrus.common.loader.Loader;
import com.alibaba.citrus.common.pair.Pair;
import com.alibaba.citrus.cr.platform.enhance.facade.service.diff.common.Date2LocalDateTimeUtils;
import com.alibaba.citrus.trail.log.LogEntry;
import com.alibaba.citrus.trail.store.LogStore;

import org.apache.commons.collections4.CollectionUtils;

/**
 * @author: qiaojiange
 * @create: 2022/01/30
 * @Description 抽象的 diff check 类
 */
public abstract class AbstractDiffCheck {


    abstract void doHandlerLog(Pair<Integer, List<LogEntry>> pair) ;

    /**
     * 做遍历
     * @param condition 查询条件
     * @param startDate 查询的开始时间
     * @param endDate 查询的结束时间
     */
    public void doTraverse(String condition , Date startDate , Date endDate) {
        LogStore logStore = Loader.loadSingle(LogStore.class);
        /**
         * @param logStore  集成日志 使用 api_adaptor_store
         * @param condition 查询条件，查询语法参考
         * {@link https://help.aliyun.com/document_detail/29060.htm?spm=a2c4g.11186623.0.0.4ff71edf8WwJ9C#concept-tnd-1jq-zdb}
         * @param topic 集成日志使用 api_adaptor
         * @param fromTime 查询开始时间
         * @param toTime 查询结束时间
         * @param line 查询的条目数量
         * @param offset 查询日志的偏移量
         * @return Pair
         * 		left : 总条目数量
         *      right : 日志明细
         */
        int start = 0;
        int limit = 100;
        Pair<Integer, List<LogEntry>> pair = logStore.find("api_adaptor_store", condition, "api_adaptor",
                Date2LocalDateTimeUtils.parse(startDate),
                Date2LocalDateTimeUtils.parse(endDate), limit, start);

        if (Objects.nonNull(pair)) {
            Integer total = pair.left();
            Integer count = 0;
            boolean isFirst = true;
            while (Objects.nonNull(total) && total > 0 && count < total) {
                if (!isFirst) {
                    pair = logStore.find("api_adaptor_store", condition, "api_adaptor",
                            Date2LocalDateTimeUtils.parse(startDate),
                            Date2LocalDateTimeUtils.parse(endDate), limit, start);
                } else {
                    isFirst = false;
                }
                //do something
                doHandlerLog(pair);

                //总计次数
                count += CollectionUtils.isNotEmpty(pair.right()) ? pair.right().size() : 0;
                start += limit;
            }
        }
    }
}
